<template>
    <div class="gis3">
        <div class="func-btns">
            <!-- 画一条线 -->
            <el-button type="primary" @click="drawLine">画一条线</el-button>

            <!-- 画一个多边形 -->
            <el-button type="primary" @click="drawPolygon">画一个多边形</el-button>

            <!-- 画一个圆 -->
            <el-button type="primary" @click="drawCircle">画一个圆</el-button>

            <!-- 极坐标系 -->
            <el-button type="primary" @click="drawPolar">极坐标系</el-button>

            <!-- 飞行到经纬度 -->
            <el-button type="primary" @click="flyTo">flyTo</el-button>

            <!-- 动态标注 -->
            <el-button type="primary" @click="addMarker">动态标注</el-button>

            <!-- 热力图 -->
            <el-button type="primary" @click="addHeatmap">热力图</el-button>

            <!-- 添加一个城市图层 -->
            <el-button type="primary" @click="addCityLayer">添加一个城市图层</el-button>

            <!--  -->
        </div>

        <!-- 地图 -->
        <Map ref="map" :access-token="accessToken" map-id="map3" :options="options" @load="handleMapLoad"
            @click="handleMapClick" />

        <!-- <Map ref="map2" :access-token="accessToken" map-id="map34" :options="options" @click="handleMapClick" /> -->
    </div>
</template>

<script setup lang="ts">
import mapboxgl from 'mapbox-gl'
import MapPopop from '@/components/MapPopop.vue'
const accessToken = '6'
const gaodeStyle = {
    "version": 8,
    "sources": {
        "gaode": {
            "type": "raster",
            "tiles": [
                // "https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
                // "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
                // "https://webst03.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
                // "https://webst04.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",


                "http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",

                // 'https://webst01.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}',
                // 'http://online{s}.map.bdimg.com/onlinelabel/?qt=tile&x={x}&y={y}&z={z}',
                // 'https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}.png',
                // 'https://server.arcgisonline.com/arcgis/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}.png',
                // 'http://online{s}.map.bdimg.com/tile/?qt=tile&x={x}&y={y}&z={z}&styles=sl'
            ],
            "tileSize": 256,
            "minzoom": 1,
            "maxzoom": 18
        }
    },
    "layers": [
        {
            "id": "gaode-layer",
            "type": "raster",
            "source": "gaode",
            "minzoom": 1,
            "maxzoom": 18
        }
    ]
}
const options = ref({
    projection: 'globe',
    zoom: 2.2,
    center: [109, 29],
    // 使用高德地图瓦片
    style: gaodeStyle,
    // style: 'mapbox://styles/mapbox/streets-v11',
    // style: 'mapbox://styles/mapbox/outdoors-v11',

})

const map: any = useTemplateRef('map')

// 地图组件暴露的地图实例
const $map: any = computed(() => map.value.$map)

const handleMapLoad = (map: mapboxgl.Map) => {
    map.on('click', 'province-layer', (e: any) => {
        debugger
        const props = e.features[0].properties;
        new mapboxgl.Popup()
            .setLngLat(e.lngLat)
            .setHTML(`
      <h3>${props.name}</h3>
      <table>
        <tr><td>GDP:</td><td>${props.gdp} 亿元</td></tr>
        <tr><td>人口1:</td><td>${props.population} 万</td></tr>
        <tr><td>增长率:</td><td>${props.growth_rate}%</td></tr>
      </table>
    `)
            .addTo(map);
    });

    map.on('click', (e: any) => {
        ElMessage.success(`点击了地图坐标: ${e.lngLat.toString()}`)
    })
}




const drawLine = () => {
    $map.value.addSource('line', {
        type: 'geojson',
        data: {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: 'LineString',
                        coordinates: [
                            [110.2191, 30.2202],
                            [117.2191, 39.2202]
                        ]
                    },
                    properties: {
                        title: 'Hello World!'
                    }
                }
            ]
        }
    })

    $map.value.addLayer({
        id: 'line',
        type: 'line',
        source: 'line',
        paint: {
            'line-color': '#f00',
            'line-width': 2
        }
    })
}

const drawPolygon = () => {
    if ($map.value.getLayer('polygon')) {
        $map.value.removeLayer('polygon')
        $map.value.removeSource('polygon')
    }

    $map.value.loadImage('https://img2.baidu.com/it/u=3513771189,694029089&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1740589200&t=28e081dcf77de67f6ab6e2af86d2251b', (error: any, image: any) => {
        if (error) throw error;
        $map.value.addImage('my-pattern', image); // 注册为可用的图标
    });

    $map.value.addSource('polygon', {
        type: 'geojson',
        data: {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: 'Polygon',

                        // 正方形
                        coordinates: [
                            [
                                [80.2191, 50.2202],
                                [117.2191, 50.2202],
                                [117.2191, 20.2202],
                                [80.2191, 20.2202]
                            ]
                        ]
                    },
                    properties: {
                        title: 'Hello World!'
                    }
                }
            ]
        }
    })

    $map.value.addLayer({
        id: 'polygon',    // 图层ID 必须唯一
        type: 'fill',     // 图层类型 如 circle, line, fill 等）
        source: 'polygon', //  引用的数据源 ID（需提前通过 map.addSource() 添加）

        // 
        paint: {
            'fill-color': '#006dff',
            'fill-opacity': 0.5,
            'fill-outline-color': '#bfa',
            'fill-pattern': 'my-pattern'
        }
    })

    // const popup = new mapboxgl.Popup({ offset: 0, className: 'my-map-popup', closeOnClick: false, maxWidth: 'none', closeButton: false })
    // // 鼠标移动到polygon图层上的事件
    // $map.value.on('mousemove', 'polygon', (e: mapboxgl.MapMouseEvent) => {
    //     const features = $map.value.queryRenderedFeatures(e.point, { layers: ['polygon'] })
    //     if (features.length) {
    //         const feature = features[0]

    //         const comp: any = createApp(MapPopop, {
    //             infos: {
    //                 lngLat: e.lngLat,
    //                 point: e.point,
    //                 feature: feature
    //             }
    //         })
    //         const div = document.createElement('div')
    //         div.className = 'aaa bbb'
    //         comp.mount(div)
    //         popup.setLngLat(e.lngLat).setDOMContent(comp._container).addTo($map.value)
    //     }
    // })

    // // 移出 关闭弹窗
    // $map.value.on('mouseleave', 'polygon', () => {
    //     popup.remove()
    // })
}

const drawCircle = () => {
    // 判断是否有圆图层
    if ($map.value.getLayer('circle')) {
        $map.value.removeLayer('circle')
        $map.value.removeSource('circle')
    }

    $map.value.addSource('circle', {
        type: 'geojson',
        data: {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                        coordinates: [110.2191, 30.2202]
                    },
                    properties: {
                        title: 'Hello World!'
                    }
                }
            ]
        }
    })

    $map.value.addLayer({
        id: 'circle',
        type: 'circle',
        source: 'circle',
        paint: {
            'circle-color': '#006dff',
            'circle-radius': 10,

        },

    })
}

// 极坐标系
const drawPolar = () => {

    if ($map.value.getLayer('polar')) {
        $map.value.removeLayer('polar')
        $map.value.removeSource('polar')
    }

    $map.value.addSource('polar', {
        type: 'geojson',
        data: {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                        coordinates: [110.2191, 30.2202]
                    },
                    properties: {
                        title: 'Hello World!'
                    }
                }
            ]
        }
    })

    $map.value.addLayer({
        id: 'polar',
        type: 'circle',
        source: 'polar',
        paint: {
            'circle-color': '#f00',
            'circle-radius': 10
        }
    })
}

const flyTo = () => {
    // 武汉市经纬度
    $map.value.flyTo({
        center: [114.3165, 30.5266],
        zoom: 8
    })
}

const addMarker = () => {

    //如果之前有标注 先清除之前的标注
    if ($map.value.getLayer('point')) {
        $map.value.removeLayer('point')
        $map.value.removeSource('marker')
    }

    $map.value.addSource('marker', {
        type: 'geojson',
        data: {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                        coordinates: [110.2191, 30.2202]
                    },
                    properties: {
                        title: 'Hello World!'
                    }
                }
            ]
        }
    })

    $map.value.addLayer({
        id: 'point',
        type: 'circle',
        source: 'marker',
        paint: {
            'circle-color': '#f00',
            'circle-radius': 10
        }
    })
}

// 热力图 范围大一些
const addHeatmap = () => {
    // 如果之前有热力图 先清除之前的热力图
    if ($map.value.getLayer('heatmap')) {
        $map.value.removeLayer('heatmap')
        $map.value.removeSource('heatmap')
    }

    // 数据源范围尽量大
    $map.value.addSource('heatmap', {
        type: 'geojson',
        data: {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                        coordinates: [110.2191, 30.2202]
                    },
                    properties: {
                        title: 'Hello World!'
                    }
                }
            ]
        }
    })


    $map.value.addLayer({
        id: 'heatmap',
        type: 'heatmap',
        source: 'heatmap',
        paint: {
            'heatmap-radius': 20,
            'heatmap-intensity': 0.9,
            'heatmap-color': [
                'interpolate',
                ['linear'],
                ['heatmap-density'],
                0, 'rgba(255, 0, 0, 0)',
                0.1, 'rgb(255, 0, 0)',
                0.3, 'rgb(255, 255, 0)',
                0.5, 'rgb(0, 255, 0)',
                0.7, 'rgb(0, 255, 255)',
                0.9, 'rgb(0, 0, 255)',
                1, 'rgb(255, 0, 255)'
            ]
        }
    })
}

// -----------------------------------------------------------------------
// 创建地图弹窗组件
const popup = new mapboxgl.Popup({ offset: 0, className: 'my-map-popup', closeOnClick: false, maxWidth: 'none', closeButton: false })

// 地图点击事件
const handleMapClick = (e: mapboxgl.MapMouseEvent) => {
    // const comp: any = createApp(MapPopop, {
    //     infos: {
    //         lngLat: e.lngLat,
    //         point: e.point,
    //     }
    // })
    // const div = document.createElement('div')
    // div.className = 'aaa bbb'
    // comp.mount(div)
    // popup.setLngLat(e.lngLat).setDOMContent(comp._container).addTo($map.value)

}

const addCityLayer = () => {
    // 加载城市图层
    // 加载GeoJSON
    $map.value.addSource('province-data', {
        type: 'geojson',
        // data: 'https://geo.datav.aliyun.com/areas_v3/bound/420000_full_district.json'
        data: 'https://geo.datav.aliyun.com/areas_v3/bound/420900_full.json'
    });

    // 基础样式层
    $map.value.addLayer({
        id: 'province-layer',
        type: 'fill',
        source: 'province-data',
        paint: {
            'fill-color': '#3498db',
            'fill-opacity': 0.5
        }
    });

    // 边界线层
    $map.value.addLayer({
        id: 'border-layer',
        type: 'line',
        source: 'province-data',
        paint: {
            'line-color': 'red',
            'line-width': 1
        }
    });



}

</script>

<style lang="less" scoped>
.gis3 {
    height: 100%;
    width: 100%;
    position: relative;

    .func-btns {
        position: absolute;
        top: 10px;
        right: 10px;
        z-index: 1000;
    }

    .aaa.bbb {
        color: red;
    }
}
</style>